<template>
  <div class="ReportCase">
    <van-overlay :show="vLoading" style="z-index:20000">
      <van-loading style="margin-left:49%; margin-top:50%" />
    </van-overlay>
    <van-nav-bar :title="$route.query.view ? '报案详情' : '报案'" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">

      <van-row type="flex" justify="space-between">
        <van-col span="12">
          <div class="title" style="margin: 12px 16px; font-size: 16px">
            理赔账号信息
          </div>
        </van-col>
        <van-col v-if="!$route.query.view" span="12"><van-button @click="insurerClick" native-type="button" style="float: right; margin: 4px 16px 0 0" plain hairline type="info"
            size="small">常用</van-button></van-col>
      </van-row>
      <van-field v-model="accountName" required label="开户名称" placeholder="请输入开户名称" :rules="[{ required: true, message: '请输入开户名称' }]" />
      <van-field readonly clickable required name="picker" :value="accountType" label="开户类型" placeholder="请选择开户类型" :rules="[{ required: true, message: '请选择开户类型' }]"
        @click="showAccountTypePicker = true" />
      <van-popup v-model="showAccountTypePicker" position="bottom">
        <van-picker show-toolbar :columns="accountTypeList.map((item) => item.label)" @confirm="onAccountTypeConfirm" @cancel="showAccountTypePicker = false" />
      </van-popup>
      <van-field readonly clickable required name="picker" :value="areaName" label="地区" placeholder="请选择地区" :rules="[{ required: true, message: '请选择地区' }]" @click="showAreaPicker = true" />
      <van-popup v-model="showAreaPicker" position="bottom">
        <van-search v-model="selectValue" @input="selectValueChange" placeholder="请输入搜索关键词" />
        <van-picker show-toolbar :columns="areaList.map((item) => item.areaName)" @confirm="onConfirm" @cancel="() => { showAreaPicker = false, setAreaList() }" />
      </van-popup>
      <van-field readonly clickable required name="picker" :value="bankName" label="地区银行" placeholder="请选择地区银行" :rules="[{ required: true, message: '请选择地区银行' }]" @click="showBankPicker = true" />
      <van-popup v-model="showBankPicker" position="bottom">
        <van-search v-model="selectBankValue" @input="bankValueChange" placeholder="请输入搜索关键词" />
        <van-picker show-toolbar :columns="bankList.map((item) => item.bankName)" @confirm="onBankConfirm" @cancel="() => { showBankPicker = false, setBankList() }" />
      </van-popup>
      <van-field readonly clickable required name="picker" :value="bankBranchName" label="分支行名称" placeholder="请选择分支行" :rules="[{ required: true, message: '请选择分支行' }]"
        @click="showbankBranchPicker = true" />
      <van-popup v-model="showbankBranchPicker" position="bottom">
        <van-search v-model="selectBankBranchValue" @input="bankValueBranchChange" placeholder="请输入搜索关键词" />
        <van-picker show-toolbar :columns="bankBranchList.map((item) => item.bankBranchName)" @confirm="onbankBranchConfirm" @cancel="() => { showbankBranchPicker = false, setBankBranchList() }" />
      </van-popup>
      <van-field v-model="accountNumber" required label="卡号" placeholder="请输入卡号" :rules="[
            { required: true, message: '请输入卡号' },
            {
                validator: (value, rule) => checkBankNumber(value, rule),
                message: '卡号只能为数字',
            },
        ]" />
      <van-field v-model="contactPhone" required label="联系方式" placeholder="请输入联系地址" :rules="[
            { required: true, message: '请输入联系地址' },
            {
                validator: (value, rule) => phoneNumberRight(value, rule),
                message: '请输入正确的手机号码',
            },
        ]" />
      <van-field v-model="certificateNumber" required label="证件号码" placeholder="请输入证件号码" :rules="[
            { required: true, message: '请输入证件号码' },
            // {
            //   validator: (value, rule) => checkDocument(value, rule),
            //   message: '请输入正确的证件号码',
            // },
        ]" />

      <van-row type="flex" justify="space-between">
        <van-col span="12">
          <div class="title" style="margin: 12px 16px; font-size: 16px">
            报案信息
          </div>
        </van-col>
      </van-row>
      <!-- <van-field v-model="username" required label="保单号" placeholder="请输入"
                :rules="[{ required: true, message: '请输入保单号' }]" /> -->
      <van-field v-model="goodsName" readonly required label="货物名称" placeholder="请输入" :rules="[{ required: true, message: '请输入货物名称' }]" />
      <van-field v-model="containerNumber" :required="!isHighway" readonly rows="3" type="textarea" @click="showContainerNumber = true" label="出险箱号" :placeholder="$route.query.view ? '' : '请输入'"
        :rules="[
            { required: !isHighway, message: '请选择出险箱号' },
        ]" />
      <van-popup v-if="!$route.query.view" v-model="showContainerNumber" position="bottom">
        <van-picker show-toolbar :columns="containerNumberList" @confirm="onContainerNumberConfirm" @cancel="() => { showContainerNumber = false }" />
        <div style="position: absolute;top: 15px;font-size: 14px;left: 48%;z-index: 2000;" @click="cancelSelection">
          取消选择
        </div>
      </van-popup>
      <van-field v-model="lossFee" required label="损失金额" placeholder="请输入" :rules="[{ required: true, message: '请输入损失金额' }, {
            validator: (value, rule) => checkLossFee(value, rule), message: '请输入数字',
        }]" />
      <van-field v-model="sceneName" readonly required label="现场联系人" placeholder="请选择" :rules="[{ required: true, message: '请输入现场联系人' }]" />
      <van-field v-model="scenePhone" readonly required label="联系方式" placeholder="请输入" :rules="[{ required: true, message: '请输入联系方式' }]" />

      <van-field v-model="reportPlace" required label="出险地址" placeholder="请输入" :rules="[{ required: true, message: '请输入出险地址' }]" />
      <van-field v-model="reportCause" rows="3" type="textarea" required label="出险原因" placeholder="请选择" :rules="[{ required: true, message: '请输入出险原因' }]" />

      <van-field v-model="explain" required rows="3" autosize label="损失情况说明" type="textarea" placeholder="请输入损失情况说明" show-word-limit />
      <div style="margin: 16px;" v-if="!$route.query.view">
        <van-button block type="info" native-type="submit">确定</van-button>
      </div>
      <div style="margin: 16px;" v-if="!$route.query.view">
        <van-button native-type="button" @click="() => { $router.push({ path: '/guaranteeSlip' }) }" block>取消</van-button>
      </div>
      <div style="margin: 16px;" v-if="!!$route.query.view">
        <van-button native-type="button" @click="() => { $router.push({ path: '/settlementOfClaim' }) }" block>返回</van-button>
      </div>
    </van-form>
    <van-popup v-model="insureShow" position="bottom" closeable :style="{ height: '60%', 'background-color': 'rgb(237 237 237)' }">
      <div style="font-size: 16px; margin: 20px 20px 14px 16px">常用理赔账号</div>

      <div v-if="!accountList.length">
        <div style="font-size:14px;padding:20px">您还未添加理赔账号，点击可添加理赔账号</div>
        <van-button style="margin-left:20px" type="primary" size="small" @click="() => {
            $router.push(`/addBankAccount?orderNum=${$route.query.orderNum}`)
            setInsuranceDataToCache()
        }">添加理赔账号</van-button>
      </div>
      <van-cell-group inset class="account-info" style="margin-top: 10px" v-for="(item, index) in accountList" :key="index">
        <van-cell>
          <template #title>
            <van-checkbox @click="insureNameChange(item)" v-model="item.isTrue"></van-checkbox>
          </template>
        </van-cell>
        <van-cell title="开户名称" :value="item.accountName" />
        <van-cell title="开户类型" :value="item.accountType" />
        <van-cell title="地区" :value="item.areaName" />
        <van-cell title="地区银行" :value="item.bankName" />
        <van-cell title="分支行名称" :value="item.bankBranchName" />
        <van-cell title="卡号" :value="item.accountNumber" />
        <van-cell title="联系方式" :value="item.contactPhone" />
        <van-cell title="证件号码" :value="item.certificateNumber" />
      </van-cell-group>
      <van-row v-if="accountList.length">
        <van-col span="24">
          <div style="float: right; margin: 16px 14px 16px 0">
            <van-button size="small" type="info" style="margin-right: 5px" @click="insureSure">确定</van-button>
            <van-button size="small" @click="() => (insureShow = false)">取消</van-button>
          </div>
        </van-col>
      </van-row>
    </van-popup>
  </div>
</template>

<script>
const regExp = /^\d+$/;
const reg5 = /^\d*\.?\d+$/;
const reg =
  /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;
const reg4 = /^[A-Z]{4}\d{7}$/;
import { AccountTypeList } from "@/utils/options";
// import { getValue } from "@/utils/func";
export default {
  name: "home",
  watch: {
    areaName: {
      handler() {
        this.getBankBranchList();
      },
      immediate: true,
    },
    bankName: {
      handler() {
        this.getBankBranchList();
      },
      immediate: true,
    },
  },
  data() {
    return {
      vLoading: false,
      isHighway: false,
      containerNumberList: [],
      showContainerNumber: false,
      accountTypeList: AccountTypeList,
      accountList: [],
      accountName: "",
      accountType: "个人",
      areaName: "",
      bankName: "",
      bankBranchName: "",
      accountNumber: "",
      contactPhone: "",
      certificateNumber: "",
      username: "",
      password: "",
      uploader: [{ url: "https://img01.yzcdn.cn/vant/leaf.jpg" }],

      insureShow: false,
      showAccountTypePicker: false,
      showAreaPicker: false,
      selectValue: "",
      areaList: [],
      showBankPicker: false,
      selectBankValue: "",
      bankList: [],
      showbankBranchPicker: false,
      selectBankBranchValue: "",
      bankBranchList: [],

      goodsName: "", // String 货物名称
      containerNumber: "", // String 出险箱号
      reportPlace: "", // String 出险地点
      reportCause: "", // String 出险原因
      sceneName: "", // String 现场联系人
      scenePhone: "", // String 联系方式
      lossFee: "", // BigDecimal 损失金额
      explain: "", // String 情况说明

      containerNumberArr: [],
    };
  },
  methods: {
    checkLossFee(val) {
      return reg5.test(val);
    },
    cancelSelection() {
      this.containerNumber = "";
      this.showContainerNumber = false;
    },
    onContainerNumberConfirm(val) {
      const arr = [];
      if (!this.containerNumberArr.includes(val)) {
        this.containerNumberArr.push(val);
      }
      this.containerNumber = this.containerNumberArr.join("\n");
      this.showContainerNumber = false;
    },
    checkContainerNumber(val) {
      let flag = true;
      const valArr = val.split(/\r?\n/g);
      valArr.forEach((item) => {
        if (item && !reg4.test(item)) {
          flag = false;
        }
      });
      return flag;
    },
    insurerClick() {
      this.insureShow = true;
    },
    bankValueBranchChange(val) {
      this.bankBranchList = this.oriBankBranchList.filter((item) => {
        if (val) {
          return item.bankBranchName.includes(val);
        } else {
          return item;
        }
      });
    },
    bankValueChange(val) {
      this.bankList = this.oriBankList.filter((item) => {
        if (val) {
          return item.bankName.includes(val);
        } else {
          return item;
        }
      });
    },
    selectValueChange(val) {
      this.areaList = this.oriAreaList.filter((item) => {
        if (val) {
          return item.areaName.includes(val);
        } else {
          return item;
        }
      });
    },
    checkBankNumber(val) {
      return regExp.test(val);
    },
    phoneNumberRight(val) {
      return /^1[3-9]\d{9}$/.test(val);
    },
    checkDocument(value) {
      return reg.test(value);
    },
    onAccountTypeConfirm(value) {
      this.accountType = value;
      this.showAccountTypePicker = false;
    },
    onbankBranchConfirm(value) {
      if (value) {
        this.bankBranchName = value;
        this.setBankBranchList();
      }
      this.showbankBranchPicker = false;
    },
    onBankConfirm(value) {
      if (value !== this.bankName) {
        this.bankBranchName = "";
      }
      this.bankName = value;
      this.showBankPicker = false;
      this.setBankList();
    },
    onConfirm(value) {
      if (value !== this.areaName) {
        this.bankBranchName = "";
      }
      this.areaName = value;
      this.showAreaPicker = false;
      this.setAreaList();
    },
    setAreaList() {
      this.selectValue = "";
      this.areaList = Object.assign(this.oriAreaList);
    },
    setBankList() {
      this.selectBankValue = "";
      this.bankList = Object.assign(this.oriBankList);
    },
    setBankBranchList() {
      this.selectBankBranchValue = "";
      this.bankBranchList = Object.assign(this.oriBankBranchList);
    },
    getAreaList() {
      return this.$get("/bank/account/area").then((res) => {
        this.areaList = res.data;
        this.oriAreaList = Object.assign(res.data);
      });
    },
    getBankList() {
      return this.$get("/bank/account/bank").then((res) => {
        this.bankList = res.data;
        this.oriBankList = Object.assign(this.bankList);
      });
    },
    getBankBranchList() {
      if (
        !this.areaName ||
        !this.bankName ||
        !this.areaList.length ||
        !this.bankList.length
      ) {
        return;
      }

      const bankItem = this.bankList.find(
        (item) => item.bankName === this.bankName
      );
      const params = {
        areaId: this.areaList.find((item) => item.areaName === this.areaName)
          .areaId,
        bankId: bankItem ? bankItem.bankId : "",
      };
      this.$get("/bank/account/bankbranch", params).then((res) => {
        this.bankBranchList = res.data;
        this.oriBankBranchList = Object.assign(res.data);
      });
    },
    setInsuranceDataToCache() {
      localStorage.setItem(
        "reportingCaseData",
        JSON.stringify(this.getParams())
      );
    },
    insureNameChange(item) {
      this.accountList.forEach((a) => {
        if (a.bankAccountId === item.bankAccountId) {
          this.$set(item, "isTrue", !a.isTrue);
          item.isTrue = !a.isTrue;
        } else {
          this.$set(a, "isTrue", false);
          a.isTrue = false;
        }
      });
    },
    getApplicantList() {
      this.$get("/bank/account/list").then((res) => {
        if (res && res.code * 1 === 200) {
          this.accountList = res.data;
          this.accountList.forEach((item) => {
            this.$set(item, "isTrue", false);
          });
        } else {
          this.accountList = [];
        }
      });
    },
    onClickLeft() {
      if (this.$route.query.view) {
        this.$router.push("/settlementOfClaim");
      } else {
        this.$router.push("/guaranteeSlip");
      }
    },
    onSubmit() {
      const url = "/warranty/insure/report";
      const message = "操作成功";
      if (this.vLoading) {
        return;
      }
      this.vLoading = true;
      this.$post(url, this.getParams())
        .then(() => {
          this.$toast({
            message,
            duration: 800,
          });
          localStorage.setItem(
            "accountData",
            JSON.stringify(this.getAccountData())
          );
          this.$router.push({
            path: "/settlementOfClaim",
          });
        })
        .finally(() => {
          this.vLoading = false;
        });
    },
    insureSure() {
      this.accountList.forEach((item) => {
        if (item.isTrue) {
          this.accountType =
            item.accountType == "1"
              ? "企业"
              : item.accountType == "2"
              ? "个人"
              : "";
          this.certificateNumber = item.certificateNumber;
          this.areaName = item.areaName;
          this.bankName = item.bankName;
          this.bankBranchName = item.bankBranchName;
          this.accountName = item.accountName;
          this.accountNumber = item.accountNumber;
          this.contactPhone = item.contactPhone;
        }
      });
      this.insureShow = false;
    },
    getAccountData() {
      const params = {
        frontReportInsure: {
          goodsName: "", // String 货物名称
          containerNumber: "", // String 出险箱号
          reportPlace: "", // String 出险地点
          reportCause: "", // String 出险原因
          sceneName: "", // String 现场联系人
          scenePhone: "", // String 联系方式
          lossFee: "", // BigDecimal 损失金额
          explain: "", // String 情况说明
        },
        frontReportInsureAccount: {
          accountType: this.accountType, //String**账户类型（1企业 2个人）  （必须）
          certificateNumber: this.certificateNumber, //String**证件号码  （必须）
          areaName: this.areaName, //String**地区名称  （必须）
          bankName: this.bankName, //String**银行名称  （必须）
          bankBranchName: this.bankBranchName, //String**支行名称  （必须）
          accountName: this.accountName, //String**开户名称  （必须）
          accountNumber: this.accountNumber, //String**账号  （必须）
          contactPhone: this.contactPhone, //String**收款人联系方式  （必须）
        },
      };
      return params;
    },
    getParams() {
      const params = {
        orderNum: this.$route.query.orderNum,
        frontReportInsure: {
          goodsName: this.goodsName, // String 货物名称
          containerNumber: this.containerNumber, // String 出险箱号
          reportPlace: this.reportPlace, // String 出险地点
          reportCause: this.reportCause, // String 出险原因
          sceneName: this.sceneName, // String 现场联系人
          scenePhone: this.scenePhone, // String 联系方式
          lossFee: this.lossFee, // BigDecimal 损失金额
          explain: this.explain, // String 情况说明
        },

        frontReportInsureAccount: {
          accountType:
            this.accountType == "企业"
              ? "1"
              : this.accountType == "个人"
              ? "2"
              : "", //String**账户类型（1企业 2个人）  （必须）
          certificateNumber: this.certificateNumber, //String**证件号码  （必须）
          areaName: this.areaName, //String**地区名称  （必须）
          bankName: this.bankName, //String**银行名称  （必须）
          bankBranchName: this.bankBranchName, //String**支行名称  （必须）
          accountName: this.accountName, //String**开户名称  （必须）
          accountNumber: this.accountNumber, //String**账号  （必须）
          contactPhone: this.contactPhone, //String**收款人联系方式  （必须）
        },
      };
      return params;
    },
    setDetail(res) {
      this.goodsName = res.frontReportInsure.goodsName; // String 货物名称
      this.containerNumber = res.frontReportInsure.containerNumber; // String 出险箱号
      this.reportPlace = res.frontReportInsure.reportPlace; // String 出险地点
      this.reportCause = res.frontReportInsure.reportCause; // String 出险原因
      this.sceneName = res.frontReportInsure.sceneName; // String 现场联系人
      this.scenePhone = res.frontReportInsure.scenePhone; // String 联系方式
      this.lossFee = res.frontReportInsure.lossFee; // BigDecimal 损失金额
      this.explain = res.frontReportInsure.explain; // String 情况说明

      this.accountType =
        res.frontReportInsureAccount.accountType == "1" ? "企业" : "个人"; //String**账户类型（1企业 2个人）  （必须）
      this.certificateNumber = res.frontReportInsureAccount.certificateNumber; //String**证件号码  （必须）
      this.areaName = res.frontReportInsureAccount.areaName; //String**地区名称  （必须）
      this.bankName = res.frontReportInsureAccount.bankName; //String**银行名称  （必须）
      this.bankBranchName = res.frontReportInsureAccount.bankBranchName; //String**支行名称  （必须）
      this.accountName = res.frontReportInsureAccount.accountName; //String**开户名称  （必须）
      this.accountNumber = res.frontReportInsureAccount.accountNumber; //String**账号  （必须）
      this.contactPhone = res.frontReportInsureAccount.contactPhone; //String**收款人联系方式  （必须）
    },
    getDetail() {
      this.$post("/warranty/insure/info", {
        orderNum: this.$route.query.orderNum,
      }).then((res) => {
        if (res && res.code * 1 === 200) {
          this.goodsName = res.data.goodsName; // String 货物名称
          this.containerNumberList = res.data.containerNumber
            ? res.data.containerNumber.split(";")
            : []; // String 出险箱号
          this.sceneName = res.data.contactName; // String 现场联系人
          this.scenePhone = res.data.contactPhone; // String 联系方式

          this.isHighway = res.data.templateName.includes("公路");
        }
      });
    },
  },
  mounted() {
    this.getApplicantList();
    this.getAreaList();
    this.getBankList();
    this.getBankBranchList();
    if (this.$route.query.getReportingCaseDataFromCache) {
      const reportingCaseData = localStorage.getItem("reportingCaseData");
      this.setDetail(JSON.parse(reportingCaseData));
    } else {
      const accountData = localStorage.getItem("accountData");
      if (accountData) {
        this.setDetail(JSON.parse(accountData));
      }
    }
    if (!this.$route.query.view) {
      this.getDetail();
    } else {
      const reportCaseDetal = localStorage.getItem("reportCaseDetal");
      this.setDetail(JSON.parse(reportCaseDetal));
    }
  },
};
</script>
<style scoped>
.ReportCase {
  background-color: #f5f5f5;
  height: 100%;
  width: 100%;
}
</style>
